<template>
  <div>
    <div ref="main" style="height:calc(100vh - 85px);width: 100%;overflow-y: hidden">
      <div style="position: absolute;top: 100px;z-index: 1000;left: 13px">
        <el-form
          :inline="true"
        >
          <el-form-item>
            <product-series-cascade @change="productChange"/>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="status"
              style="width: 100px;"
              :placeholder="$t('status')"
              @change="statusChange"
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="geoHash" @change="listDeviceGEO">
              <el-option
                v-for="item in geoHashList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :icon="showList?'el-icon-caret-left':'el-icon-caret-right'"
              @click="showList=!showList"
            />
          </el-form-item>
          <el-form-item v-if="!zooMax">
            <el-button type="warning" icon="el-icon-full-screen" @click="requestFullScreen"/>
          </el-form-item>
          <el-form-item v-else>
            <el-button type="warning" icon="el-icon-crop" @click="exitFullscreen"/>
          </el-form-item>
        </el-form>
        <div v-show="showList" style="background: white;padding: 10px;border-radius: 10px">
          <div class="uni-scroll" style="height:calc(100vh - 190px);">
            <el-table
              ref="deviceTable"
              :show-header="false"
              :data="deviceList"
              style="width: 100%;"
              highlight-current-row
              @cell-click="deviceClick"
            >
              <el-table-column width="50">
                <template slot-scope="scope">
                  <el-image
                    slot="reference"
                    style="width: 40px; height:40px;margin: 8px 0 0 0"
                    :src="scope.row.iconUrl"
                    fit="fit"
                  />
                </template>
              </el-table-column>
              <el-table-column>
                <template slot-scope="scope">
                  <div style="">
                    <div :class="scope.row.status" style="font-size:13px;line-height: 18px;">
                      <span>{{ scope.row.deviceName }}</span>
                      <span style="font-size:12px;color: #b3d3c2;">({{ scope.row.deviceCore }})</span>
                    </div>
                    <div style="font-size:12px;color: #b3d3c2; line-height: 14px;margin-top: 8px">{{
                        scope.row.address
                      }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column width="180">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: flex-end;margin-right: 5px">
                    <app-signal :signal="scope.row.signal" :status="scope.row.status"
                                :connect-type="scope.row.connectType" style="margin-right: 5px"
                    />
                    <app-surplus :device="scope.row"/>
                  </div>
                  <div style="display: flex;justify-content: flex-end">
                    <el-button-group style="margin-top: 3px">
                      <el-button round icon="el-icon-menu" @click.stop="deviceMore(scope.row)"/>
                      <el-button icon="el-icon-setting" @click.stop="deviceSetting(scope.row)"/>
                      <el-button icon="el-icon-s-platform" @click.stop="deviceSensor(scope.row)"/>
                    </el-button-group>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div ref="map" style="height:calc(100vh);width: 100%"/>
    </div>

    <el-dialog
      :visible.sync="showSetting"
      :title="device.deviceName"
      width="1200px"
      top="15px"
    >
      <device-setting
        :device-core="device.deviceCore"
        class="uni-scroll"
        style="height: 600px"
      />
    </el-dialog>

    <el-drawer
      size="70%"
      :visible.sync="drawer"
      direction="rtl"
    >
      <div class="uni-scroll" style="height: calc(100vh - 100px)">
        <sensor-camera-list :device="device"/>
      </div>
    </el-drawer>

  </div>

</template>
<script>
import { listDeviceGEO } from '@/api/iot/iotDeviceBelongApi'
import {
  getCompanyId,
  getDeptId,
  getLat,
  getLng,
  getNetModel,
  getSearchDeviceStatus,
  getShowHidden,
  setSearchDeviceStatus
} from '@/util/storage'
import {
  exitFullscreen,
  formatDate,
  formatSensorType,
  listDeviceStatus,
  listGeoHash,
  requestFullScreen
} from '@/util/common'
import {
  addMapClickListener,
  addMarketClickListener,
  clearAllMarket,
  hideInfoWindow,
  makeInfoWindow,
  makeMap,
  makeMarket,
  setCenter
} from '@/util/mapTool'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import SensorCameraList from '@/components/SensorCameraList'
import DeviceSetting from '@/components/DeviceSetting'
import ProductSeriesCascade from '@/components/ProductSeriesCascade'
import AppSurplus from '@/components/AppSurplus'
import AppSignal from '@/components/AppSignal'

let map = null
let infoWindow = null
export default {
  name: 'GeoMap',
  components: {
    AppSurplus,
    AppSignal,
    ProductSeriesCascade,
    SensorCameraList,
    DeviceSetting
  },
  data() {
    return {
      showList: false,
      deviceList: [],
      status: getSearchDeviceStatus(),
      drawer: false,
      showSetting: false,
      device: {},
      productId: null,
      seriesId: null,
      companyId: parseInt(getCompanyId()),
      deptId: null,
      isInit: false,
      netModel: getNetModel(),
      lat: getLat(),
      lng: getLng(),
      zooMax: false,
      statusList: [],
      geoHashList: listGeoHash(),
      geoHash: 3,
      showHidden: getShowHidden()
    }
  },
  mounted() {
    const that = this
    const param = this.$route.query
    const isDept = !!(param.isDept && param.isDept === '1')
    if (isDept) {
      this.deptId = parseInt(getDeptId())
    }
    this.isInit = true
    this.statusList = listDeviceStatus(this)
    map = makeMap(this.$refs.map, this.lat, this.lng)
    addMapClickListener(map, function(e) {
      that.lat = e.latLng.lat
      that.lng = e.latLng.lng
      that.listDeviceGEO()
    })
    window.mapDeviceSensor = this.mapDeviceSensor
    window.mapDeviceMore = this.mapDeviceMore
    window.mapDeviceSetting = this.mapDeviceSetting
    this.listDeviceGEO()
  },
  methods: {
    statusChange() {
      this.listDeviceGEO()
      setSearchDeviceStatus(this.status)
    },
    productChange(val) {
      this.productId = val.productId
      this.seriesId = val.seriesId
      this.listDeviceGEO()
    },
    requestFullScreen() {
      requestFullScreen(this.$refs.main)
      this.zooMax = true
    },
    exitFullscreen() {
      exitFullscreen()
      this.zooMax = false
    },
    listDeviceGEO() {
      const that = this
      clearAllMarket(map)
      const req = {
        productId: this.productId,
        seriesId: this.seriesId,
        status: this.status,
        deptId: this.deptId,
        companyId: this.companyId,
        lat: this.lat,
        lng: this.lng,
        geoHash: this.geoHash,
        fieldList: ['deviceCore', 'lat', 'lng', 'deviceName', 'iconUrl']
      }

      listDeviceGEO(req).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.pointIndex = 0
          this.makeMarkerList(data)
        }
      })
    },
    makeMarkerList(data) {
      const that = this
      setTimeout(() => {
        const dataLength = data.length
        for (let i = 0; i < 20; i++) {
          if (that.pointIndex >= dataLength) {
            return
          }
          that.makeMarker(data[that.pointIndex])
          that.pointIndex = that.pointIndex + i
        }
        that.makeMarkerList(data)
      }, 0)
    },
    makeMarker(device) {
      const marker = makeMarket(map, device.lat, device.lng, device.iconUrl)
      marker.ztn.device = device
      const that = this
      addMarketClickListener(map, marker, (param) => {
        that.deviceClick(param.marker.ztn.device)
      })
      return marker
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    mapDeviceMore(deviceCore) {
      map.ztn.markerList.forEach(marker => {
        const device = marker.ztn.device
        if (device.deviceCore === deviceCore) {
          this.deviceMore(device)
          return
        }
      })
    },
    mapDeviceSetting(deviceCore) {
      map.ztn.markerList.forEach(marker => {
        const device = marker.ztn.device
        if (device.deviceCore === deviceCore) {
          this.deviceSetting(device)
          return
        }
      })
    },
    mapDeviceSensor(deviceCore) {
      map.ztn.markerList.forEach(marker => {
        const device = marker.ztn.device
        if (device.deviceCore === deviceCore) {
          this.deviceSensor(device)
          return
        }
      })
    },
    deviceSensor(item) {
      this.deviceClick(item)
      this.drawer = true
    },
    deviceMore(item) {
      this.$router.push({
        path: '/device/manage/' + item.deviceCore,
        query: {
          deviceCore: item.deviceCore,
          deviceName: item.deviceName
        }
      })
    },
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    deviceSetting(item) {
      this.deviceClick(item)
      this.showSetting = true
    },
    listSensorWith(device) {
      const that = this
      listSensorWith({
        deviceCore: device.deviceCore,
        withExplain: true,
        withParam: true,
        withSetting: false
      }).then(res => {
        const { code, data } = res
        const sensorList = []
        if (code === '200') {
          for (const item of data) {
            if (item.hidden) {
              continue
            }
            if (!item.explainList) {
              item.explainList = []
            }
            if (!item.paramList) {
              item.paramList = []
            }
            if (item.explainList.length > 0 || item.paramList.length > 0) {
              sensorList.push(item)
            }
          }
        }
        that.showMapInfo(device, sensorList)
      })
    },
    showMapInfo(device, sensorList) {
      let content = `<div style="width: 200px">
                      <div>${device.deviceName}</div>`

      sensorList.forEach(sensor => {
        if (this.showHidden !== '1' && sensor.hidden) {
          return
        }
        content = content + `<div style="margin: 13px 0;font-size: 13px;color: #e7cc69;">
                                <span style="margin-right: 5px">${sensor.sensorName}</span>
                                <span>[${this.formatSensorType(sensor.type)}${this.$t('port')}:${sensor.port}]</span>
                              </div>`
        sensor.explainList.forEach(explain => {
          if (this.showHidden !== '1' && explain.hidden) {
            return
          }
          content = content + `<div style="height: 20px;width: 100%">
                                    <span style="color: #99a9bf;width: 100px;font-size: 13px">${explain.name}<span style="color: #606266;font-size: 13px;float: right">${explain.value}${explain.unit}</span></span>
                               </div>`
        })
      })
      content = content + `<div style="width: 100%;height: 20px;">
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-menu " style="font-size: 15px" onclick="mapDeviceMore('${device.deviceCore}')" />
                        </div>
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-setting" style="font-size: 15px" onclick="mapDeviceSetting('${device.deviceCore}')" />
                        </div>
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-s-platform" style="font-size: 15px" onclick="mapDeviceSensor('${device.deviceCore}')" />
                        </div>
                      </div>
                    </div>`
      infoWindow = makeInfoWindow(map, device.lat, device.lng, content)
    },
    deviceClick(item) {
      this.device = item
      hideInfoWindow(map, infoWindow)
      this.listSensorWith(item)
      if (this.showList) {
        for (let i = 0, j = map.ztn.markerList.length; i < j; i++) {
          if (map.ztn.markerList[i].ztn.device.deviceCore === item.deviceCore) {
            const marker = map.ztn.markerList[i]
            setCenter(map, marker.lat, marker.lng)
            return
          }
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
